<?php
/**
 * User: xuanbang.wen
 * Date: 2019/12/12
 */

namespace App\Web\Model;


use App\Service\ExternalAPI\EhireApi;
use App\Web\Facades\UserAuth;
use EchoPHP\Facades\Db;
use App\Web\Model\CustomerAccount;

class CaseContacter extends Model {
    private $tableName = 'CaseContacter';

    public function show($projectId) {
        $field = 'caseid,casename,projectid,status,caseshowname,listindex,area,hascontact,haschargeway';
        $sql = 'select ' . $field . ' from SCase where projectid = ?';
        return Db::select($sql, [$projectId]);
    }

    public function detail($caseId) {
        $sql = 'select cc.id as casecontacterid,cc.subid,cc.accountid,ca.email,ca.cname,ca.isscharger,ca.bindehire,ca.ehirectmid,ca.ehireaccid from ' . $this->tableName . ' as cc left join CustomerAccount as ca on cc.accountid = ca.id where cc.status = ? and ca.status = ? and cc.caseid = ?';
        $var = ['01', '01', $caseId];
        $result = Db::select($sql,$var);
        $customerAccountModel = new CustomerAccount();
        $contacterlist = $customerAccountModel->getContactorInfo($result);
        return $contacterlist;
    }

    public function add($account, $caseId) {

        $sql = 'select CustomerSub.subid,crmcustomerid from CustomerSub left join SCase on CustomerSub.subid = SCase.subid where caseid = ?';
        $subInfo = Db::selectOne($sql, [$caseId]);
        if (!$subInfo) {
            return ['status' => false, 'message' => '操作失败', 'validateFailure' => ['subid' => 'subid非法']];
        }
        if ($account['accountid'] == 0) {
            //查询重复
            $sql = 'select 1 from CustomerAccount where subid = ? and email = ?';
            $result = Db::selectOne($sql, [$subInfo['subid'], $account['email']]);
            if ($result) {
                return ['status' => false, 'message' => '操作失败', 'validateFailure' => ['email' => '邮箱已存在']];
            }

            if ($account['ischarger'] == 1) {
                $sql = 'select 1 from CustomerAccount where subid = ? and ischarger = ?';
                $result = Db::selectOne($sql, [$subInfo['subid'], 1]);
                if ($result) {
                    return ['status' => false, 'message' => '操作失败', 'validateFailure' => ['ischarger' => '已存在客户联系人管理员']];
                }
            }
        } else {
            //查询重复
            $sql = 'select 1 from CaseContacter where caseid = ? and accountid = ? and status = ?';
            $result = Db::selectOne($sql, [$caseId, $account['accountid'], '01']);
            if ($result) {
                return ['status' => false, 'message' => '操作失败', 'validateFailure' => ['email' => '邮箱已存在']];
            }
        }
        $result = Db::connect('jyrpo_pdo')->transaction(function () use ($account, $subInfo, $caseId) {
            if ($account['bindehire'] == 0) {
                $ehirectmId = '';
                $ehireaccId = '';
            } else {
                $ehirectmId = $account['ehirectmid'];
                $ehireaccId = $account['ehireaccid'];
            }
            $user = UserAuth::getLoginInfo();
            $accountId = $account['accountid'];
            if ($account['accountid'] == 0) {
                $accountSql = 'insert into CustomerAccount(subid,creator,updator,email,cname,isscharger,bindehire,ehirectmid,ehireaccid,crmcustomerid,status,createdate,updatedate,isinterviewer) value (?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())';
                $accountVar = [
                    $subInfo['subid'],
                    $user['userid'],
                    $user['userid'],
                    $account['email'],
                    $account['cname'],
                    $account['ischarger'],
                    $account['bindehire'],
                    $ehirectmId,
                    $ehireaccId,
                    $subInfo['crmcustomerid'],
                    '01',
                    0
                ];
                Db::connect('jyrpo_pdo')->insert($accountSql, $accountVar);
                $accountId = Db::connect('jyrpo_pdo')->getLastInsertId();
            }

            $sql = 'insert into ' . $this->tableName . ' (subid,caseid,accountid,status,creator,updator,createdate,updatedate) value (?,?,?,?,?,?,NOW(),NOW())';
            $var = [
                $subInfo['subid'],
                $caseId,
                $accountId,
                '01',
                $user['userid'],
                $user['userid'],
            ];
            return Db::connect('jyrpo_pdo')->insert($sql, $var);
        });
        return [
            'status'  => $result,
            'message' => $result ? '添加成功' : '添加失败',
        ];
    }

    public function del($caseId, $caseContacterId) {
        $sql = 'select 1 from ' . $this->tableName . ' where caseid = ? and id != ? and status = ? ';
        $otherAccount = Db::selectOne($sql, [$caseId, $caseContacterId, '01']);
        if (!$otherAccount) {
            return [
                'status'  => false,
                'message' => '不可删除此职位最后一条联系人'
            ];
        }
        $userId = UserAuth::getLoginId();
        $sql = 'update ' . $this->tableName . ' set status = ? , updator = ? , updatedate = NOW() where id = ? and status = ?';
        $var = [
            '06',
            $userId,
            $caseContacterId,
            '01'
        ];
        $result = Db::update($sql, $var);
        return [
            'status'  => $result == 1,
            'message' => $result == 1 ? '删除成功' : '删除失败',
        ];
    }

    /**
     * 职位批量添加联系人
     * @param $contactorIds
     * @param $projectId
     * @param $caseId
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function batchAddContactor($contactorIds,$projectId,$caseId) {
        $sql = 'select subid from Project where projectid = ?';
        $var = [$projectId];
        $result = Db::selectOne($sql,$var);
        if (empty($result)) {
            return [
                'status' => false,
                'message' => '项目不存在'
            ];
        }
        $subId = $result['subid'];
        $customerAccountModel = new CustomerAccount();
        //获取当前交易公司下所有联系人
        $customerAccounts = $customerAccountModel->show($subId);
        $customerAccountIds = array_column($customerAccounts,'accountid');
        //如果存在非交易公司下联系人以外的联系人，返回错误
        if (!empty($tmp = array_diff($contactorIds,$customerAccountIds))) {
            return [
                'status' => false,
                'message' => '存在非法联系人id',
                'errorcontactorids' => array_values($tmp)
            ];
        }
        //获取当前职位下已存在的联系人
        $sql = 'select accountid from CaseContacter where caseid = ? and status = ?';
        $var = [$caseId,'01'];
        $accountids = Db::select($sql,$var);
        $accountidArr = [];
        foreach ($accountids as $accountid) {
            $accountidArr[] = $accountid['accountid'];
        }

        $oprId = UserAuth::getLoginId();
        $insertSql = 'insert into CaseContacter (subid,caseid,accountid,status,creator,createdate,updator,updatedate) values';
        $insertVar = $insertVarsSql = [];
        foreach ($contactorIds as $contactorId) {
            //跳过已存在的联系人
            if (!empty($accountidArr) && in_array($contactorId,$accountidArr)) {
                continue;
            }
            $insertVarsSql[] = '(?,?,?,?,?,Now(),?,Now())';
            $insertVar = array_merge($insertVar, [
                $subId, $caseId, $contactorId, '01',$oprId,$oprId
            ]);
        }
        if (empty($insertVarsSql)) {
            return [
                'status' => false,
                'message' =>'无新增联系人'
            ];
        }
        $insertSql .= implode(',', $insertVarsSql);
        $result = Db::connect('jyrpo_pdo')->insert($insertSql, $insertVar);
        if ($result) {
            return [
                'status' => true,
                'message' =>'批量添加联系人成功'
            ];
        }
        return [
            'status' => false,
            'message' => '批量添加联系人失败'
        ];
    }

}